<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>图片竖直分割工具 - 自定义份数</title>
  <!-- 引入 JSZip 和 FileSaver -->
  <script src="https://unpkg.com/jszip@3.10.1/dist/jszip.min.js"></script>
  <script src="https://unpkg.com/file-saver@2.0.5/dist/FileSaver.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
      background: #f4f4f4;
    }
    .container {
      max-width: 900px;
      margin: auto;
      background: white;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h1 {
      text-align: center;
      color: #333;
    }
    .input-section {
      text-align: center;
      margin: 20px 0;
      font-size: 16px;
    }
    input[type="number"] {
      padding: 8px;
      font-size: 16px;
      width: 100px;
      margin: 0 10px;
    }
    button {
      padding: 10px 20px;
      font-size: 16px;
      margin: 10px;
      background: #007cba;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    button:hover {
      background: #005a87;
    }
    button:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
    .upload {
      text-align: center;
      margin: 20px 0;
    }
    .preview {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 20px;
      justify-content: center;
    }
    .piece {
      border: 1px solid #ddd;
      text-align: center;
      padding: 5px;
      width: 200px;
    }
    .piece img {
      max-width: 100%;
      height: auto;
      display: block;
    }
    .piece a {
      display: block;
      margin-top: 5px;
      font-size: 14px;
    }
    #downloadAll {
      display: block;
      margin: 20px auto;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>图片竖直分割工具（自定义份数）</h1>
    <p style="text-align:center;">上传一张图片，垂直等分为任意份数</p>

    <!-- 用户输入分割份数 -->
    <div class="input-section">
      分割成
      <input type="number" id="partsInput" min="1" value="29" />
      份
    </div>

    <div class="upload">
      <input type="file" id="imageInput" accept="image/*" />
      <br /><br />
      <button onclick="document.getElementById('imageInput').click();">
        选择图片
      </button>
    </div>

    <button id="downloadAll" disabled onclick="downloadAllAsZip()">
      📦 一键下载全部为 ZIP
    </button>

    <div id="result" style="display:none;">
      <h3>分割结果（可单独下载）：</h3>
      <div id="pieces" class="preview"></div>
    </div>
  </div>

  <script>
    let imageDataUrls = {}; // 存储每张图片的 data URL

    document.getElementById("imageInput").addEventListener("change", function (e) {
      const file = e.target.files[0];
      if (!file) return;

      const parts = parseInt(document.getElementById("partsInput").value);
      if (isNaN(parts) || parts < 1) {
        alert("请输入有效的份数（≥1）");
        return;
      }

      const reader = new FileReader();
      reader.onload = function (ev) {
        const img = new Image();
        img.onload = function () {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          const width = img.width;
          const height = img.height;
          const partHeight = Math.floor(height / parts); // 每块高度

          const piecesContainer = document.getElementById("pieces");
          piecesContainer.innerHTML = "";
          imageDataUrls = {}; // 清空旧数据

          for (let i = 0; i < parts; i++) {
            const top = i * partHeight;
            const h = (i === parts - 1) ? (height - top) : partHeight; // 最后一块包含剩余

            canvas.width = width;
            canvas.height = h;
            ctx.clearRect(0, 0, width, h);
            ctx.drawImage(img, 0, -top, width, height);

            const dataUrl = canvas.toDataURL("image/jpeg", 0.95);
            const filename = `part_${i}.jpg`;
            imageDataUrls[filename] = dataUrl;

            const div = document.createElement("div");
            div.className = "piece";

            const imgEl = document.createElement("img");
            imgEl.src = dataUrl;
            imgEl.alt = `Part ${i}`;

            const downloadLink = document.createElement("a");
            downloadLink.href = dataUrl;
            downloadLink.download = filename;
            downloadLink.textContent = `下载 第${i+1}段`;

            div.appendChild(imgEl);
            div.appendChild(downloadLink);
            piecesContainer.appendChild(div);
          }

          document.getElementById("result").style.display = "block";
          document.getElementById("downloadAll").disabled = false;
        };
        img.src = ev.target.result;
      };
      reader.readAsDataURL(file);
    });

    // 批量打包下载为 ZIP
    function downloadAllAsZip() {
      const zip = new JSZip();
      for (const [filename, dataUrl] of Object.entries(imageDataUrls)) {
        const base64 = dataUrl.split(",")[1]; // 去掉前缀
        zip.file(filename, base64, { base64: true });
      }
      zip.generateAsync({ type: "blob" }).then(function (content) {
        saveAs(content, "split_parts.zip");
      });
    }
  </script>
</body>
</html>